package com.gree.shyun.gupiao.task;

import com.gree.shyun.server.BaseAction;
import com.gree.shyun.server.actions.QuoteList.QuListAction;
import com.gree.shyun.server.actions.QuoteList.requestParam.QuListParam;
import com.gree.shyun.server.actions.QuoteList.respone.Data;
import com.gree.shyun.server.actions.QuoteList.respone.GpData;
import com.gree.shyun.server.actions.QuoteList.respone.QuListRespone;
import com.gree.shyun.server.db.DbHelper;
import com.gree.shyun.server.http.util.HttpClient;
import com.gree.shyun.server.task.Task;
import com.gree.shyun.util.CommonUtil;
import org.apache.http.HttpException;

import java.io.IOException;
import java.util.List;

public class GetGupiaoDataTask extends Task {
    @Override
    public Task doTask() {

        //先请求一下首页 绕开防爬策略
        HttpClient httpClient = HttpClient.getInstance();
        httpClient.setUrl(BaseAction.DOMAIN);
        try {
            httpClient.get();
        } catch (IOException e) {
            e.printStackTrace();
        }

        List<GpData> gpData = DbHelper.findAll(GpData.class);
        if(gpData==null||gpData.size()==0){
            getNextWidthAll();
            gpData = DbHelper.findAll(GpData.class);
        }
        setResult(gpData);
        return this;
    }

    /**
     * 加载全部分页数据
     */
    private int pageSize = 1000;
    private int pageIndex = 1;
    private int allPage = 0;
    private void getNextWidthAll(){
        QuListParam quListParam = new QuListParam();
        quListParam.setMarket("CN");//CN,
        quListParam.setSize(pageSize+"");//30,
        quListParam.setOrderby("percent");//percent,
        quListParam.setOrder_by("percent");//percent,
        quListParam.setPage(pageIndex+"");//2,
        quListParam.setType("sh_sz");//sh_sz,
        quListParam.setOrder("desc");//desc,
        QuListAction action= new QuListAction();

        try {
            QuListRespone respone = action.get(quListParam);
            Data data = respone.getData();
            //保存全部
            DbHelper.saveBindingIdAll(data.getList());
            allPage = CommonUtil.getAllPage(data.getCount(),pageSize);
        } catch (Exception e) {
            e.printStackTrace();
        }
        pageIndex++;
        if(pageIndex<allPage){
            getNextWidthAll();
        }else{
            pageIndex = 1;
        }
    }
}
